#include <iostream>
#include "Sock.hpp"
#include "Protocol.hpp"
#include <unistd.h>

using namespace ns_protocal;

static void Usage(const std::string &process)
{
    std::cout << "\nUsage: " << process << " serverIp serverPort\n"
              << std::endl;
}

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(1);
    }

    std::string server_ip(argv[1]);
    uint16_t server_port = atoi(argv[2]);
    Sock sock;

    int sockfd = sock.Socket();
    if (!sock.Connect(sockfd, server_ip, server_port))
    {
        std::cerr << "Connect error" << std::endl;
        exit(2);
    }

    bool quit = false;
    std::string buffer;
    while (!quit)
    {
        // Request req(10,20,'+');
        Request req;
        std::cout << "请输入:>#";
        std::cin >> req.x_ >> req.op_ >> req.y_;

        std::string s = req.Serialiaze();
        s = Encode(s);
        Send(sockfd, s);

        while (true)
        {
            bool res = Recv(sockfd, &buffer);
            if(!res)
            {
                quit=true;
                break;
            }
            std::string package = Decode(buffer);
            if(package.empty())
                continue;
            
            Response resp;
            resp.Deserialized(package);
            
            std::string err;
            switch (resp.code_)
            {
            case 1:
                err = "除0错误";
                break;
            case 2:
                err = "模0错误";
                break;
            case 3:
                err = "非法操作";
                break;
            default:
                std::cout << req.x_ << req.op_ << req.y_ << " = " << resp.result_ << " [success]" << std::endl;
                break;
            }
            // std::cout << "code:" << resp.code_ << std::endl;
            // std::cout << "result: " << resp.result_ << std::endl;
            // sleep(1);
            if(!err.empty())
            {
                std::cout<<err<<std::endl;
                break;
            }
        }
    }
    close(sockfd);
    return 0;
}